package com.example.chat.service.impl;

import com.example.chat.entity.FileUpload;
import com.example.chat.model.ImageUploadResp;
import com.example.chat.service.HttpService;
import com.example.common.common.config.filter.UserContext;
import com.example.common.common.enums.FileUploadEnum;
import lombok.RequiredArgsConstructor;
import com.example.chat.mapper.FileUploadMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.example.chat.service.FileService;
import com.example.common.utils.MinioUtils;

import java.time.LocalDateTime;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/6 20:46
 **/
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {

    private final MinioUtils minioUtils;
    private final FileUploadMapper fileUploadMapper;
    private final HttpService httpService;

    @Override
    public String uploadFile(MultipartFile file) {
        // 文件基础校验
        if (file == null) {
            throw new RuntimeException("文件上传为空");
        }

        // 文件服务器重复上传校验 && 数据库重复校验
        String filename = file.getOriginalFilename();
//        FileUpload existFileUpload = fileUploadMapper.queryFileUpload(null, filename);
//        if (existFileUpload != null) {
//            throw new RuntimeException("已存在相同名称文件，请修改文件名后再次上传");
//        }
        // 文件服务器上传
        String fileId = minioUtils.uploadObject(file);

        // 异步执行文件裁片向量化存储
//        httpService.processDocuments(fileId);

        // 文件上传后文件记录
        FileUpload fileUpload = FileUpload.builder()
                .fileId(fileId).originalName(filename)
                .fileType(file.getContentType())
                .fileSize(file.getSize())
                .status(FileUploadEnum.COMPLETED.getStatus())
                .uploaderId(UserContext.getCurrentUser().getUserId())
                .uploadTime(LocalDateTime.now()).build();
        fileUploadMapper.insertFileUpload(fileUpload);
        return fileId;
    }

    @Override
    public ImageUploadResp uploadImage(MultipartFile file) {
        String fileId = uploadFile(file);
        String url = minioUtils.getObjectUrl(fileId);
        return ImageUploadResp.builder()
                .fileId(fileId)
                .url(url)
                .build();
    }
}
